<template>
  <div style="height: calc(100vh - 40px);">
    <MyBar>
      <ElButton :icon="ElIconPlus" size="small" type="primary" plain @click="onNewColor">新建颜色</ElButton>
    </MyBar>

    <DialogColorEdit
      v-if="editingColor"
      v-model:model-value="colorEditing"
      :color="editingColor"
      @confirm="editConfirm"
      @delete="editDelete"/>
    
    <div flex style="height: calc(100vh - 80px);">
      <ElTabs tabPosition="left" v-model:model-value="tabGroup">
        <el-tab-pane label="颜色组" name="" :disabled="true">
          <div></div>
        </el-tab-pane>
        <ElTabPane
          v-for="(item, index) in colorGroupNames" :key="index"
          :label="item"
          :name="item"
          >
          <el-table :border="true" :data="getColorsOfGroup(item)"
            style="width: 600px; height: calc(100vh - 80px);" mb
            @row-click="onEditColor">
            <el-table-column label="名称" width="150">
              <template #default="scope">
                <div>{{ getColorDisplayName(scope.row) }}</div>
              </template>
            </el-table-column>
          </el-table>
        </ElTabPane>
      </ElTabs>
      
    </div>

  </div>
</template>

<script setup lang="ts">
import { GameColor } from '~/models/Game/GameColor';
import { TypeMathColor } from '~/models/types';
import type { VarInit } from "~/models/graph/data/var_init";
import { oProject } from '~/models/Project';

const tabGroup = ref('未分组')
const globals = computed(() => oProject.value.storage.globals)
const colors = computed(() => globals.value.filter( x => x.type.is(TypeMathColor)))

const colorGroupNames = computed(() => {
  const groupArr = colors.value.map(x => x.name.split('_')).filter(arr => arr.length > 1).map(arr => arr[0])
  groupArr.push('未分组')
  return Array.from(new Set(groupArr))
})

// In Table
function getColorsOfGroup(group: string) {
  if (group === '未分组') {
    return colors.value.filter(color => color.name.indexOf('_') < 0)
  }
  return colors.value.filter(color => {
    const arr = color.name.split('_')
    return arr.length > 1 && arr[0] === group
  })
}

function getColorDisplayName(color: GameColor) {
  const colorIndex = color.name.indexOf('_')
  if (colorIndex < 0) {
    return color.name
  }
  else {
    return color.name.slice(colorIndex+1)
  }
}


// 编辑点
const colorEditing = ref(false)
const editingColor = ref(null as null | VarInit)
function onNewColor() {
  const data: VarInit = {
    name: '',
    type: TypeMathColor,
    initialValue: TypeMathColor.default
  }
  editingColor.value = data
  colorEditing.value = true
}
function onEditColor(color: VarInit) {
  editingColor.value = color
  colorEditing.value = true
}
function editConfirm() {
  if(editingColor.value && (colors.value.indexOf(editingColor.value) < 0)) {
    globals.value.push(editingColor.value)
  }
}
function editDelete() {
  if (!editingColor.value) {
    return
  }
  lodash.remove(globals.value, x => x === editingColor.value)
}
</script>